package com.jshx.sz.gdjt.thread;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.jshx.sz.gdjt.thread.data.DataProUtil;
import com.jshx.sz.gdjt.util.AccessDBImp;
import com.jshx.sz.gdjt.util.TDESEncodeUtils;
import com.jshx.sz.gdjt.util.file.UploadItem;
import com.jshx.sz.gdjt.util.file.UploadMultiFileThread;
import com.jshx.sz.gdjt.constant.ApplicationGlobal;
import com.jshx.sz.gdjt.db.DataBaseUtil;

import android.content.pm.PackageInfo;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
 
/**
 * 登录验证通过以后同步数据
 * @author YP
 * @time 2013-08-30
 */
public class DataSynchronizedThread  extends Thread{
	private Handler handler;
	private UploadMultiFileThread uploadMultiThread;
	public DataSynchronizedThread()
	{
		
	}
	
 	public DataSynchronizedThread(Handler handler)
	{
		this.handler=handler;
	}
	public void run() 
	{
		try {
			 
			//1.同步互检人信息-----------开始
			//删除
			DataBaseUtil dao=new DataBaseUtil();
			dao.deleteCheckUser();
			this.synPerson();//增加
			//1.同步互检人信息-----------结束
			
			//2.同步任务 明细数据-----开始
			uploadMultiThread=new UploadMultiFileThread(handler1);
			uploadMultiThread.start();
			this.synTaskList();
			//2.同步任务- 明细数据----结束
			
			
			
			Message msg=new Message();
			msg.what=ApplicationGlobal.data_obtained;
			handler.sendMessage(msg) ;
		} catch (Exception e) {
			System.out.println(e);
			e.printStackTrace();
			Message msg=new Message();
			msg.what=ApplicationGlobal.data_missed;
			handler.sendMessage(msg) ;
		}  
	}
	
	private void synTaskList() throws Exception
	{
		//
		DataBaseUtil dao=new DataBaseUtil();
		ArrayList<HashMap<String, String>> list=dao. getLocalTaskList();
		if(list!=null&&list.size()>0)
		{
			for(int i=0;i<list.size();i++)
			{
				HashMap<String, String> map=list.get(i);
//				order_num,team_num,check_person,audit_person,device_num,process_orderNum ,status
				String status=map.get("status");
				String orderNo=map.get("order_num");
				String dataNumber=map.get("process_orderNum");
				String assetCode=map.get("device_num");
				String type="2";
				if(status.equals("3"))
				{
					type="4";
				}
				String workNo2="";
			
				//2.更新明细信息
				HashMap<String, String> dataMap=new HashMap<String, String>();
				dataMap.clear();
				dataMap=dao.getLocalDataByOrderNoType(orderNo,dataNumber);
				CommitDataThread thread=new CommitDataThread(dataMap, type, dataNumber, assetCode);
				thread.start();
				//3.更新图片
				//图片
				List<String> imgNameList=new ArrayList<String>();
				if(dataNumber.equals("4"))
				{
					imgNameList.clear();
					for(int j=1;j<6;j++)
					{
						if(dataMap.containsKey("cdimg"+j))
						{
							String cdimg=dataMap.get("cdimg"+j)+"";
							if(cdimg!=null&&!cdimg.equals(""))
							{
								String[] obj=cdimg.split(",");
								for(int k=0;k<obj.length;k++)
								{
									imgNameList.add(obj[k]);
								}
							}
						}
					}
					if(dataMap.containsKey("hjr_id"))
					{
						workNo2=dataMap.get("hjr_id");
					}
						
				}
				else if(dataNumber.equals("1"))
				{
					imgNameList.clear();
					if(dataMap.containsKey("hjr_id"))
					{
						workNo2=dataMap.get("hjr_id");
					}
					
					//项目
					for(int j=1;j<18;j++)
					{
						if(dataMap.containsKey("imgs"+j))//图片
						{
							String cdimg=dataMap.get("imgs"+j)+"";
							if(cdimg!=null&&!cdimg.equals("")&&!cdimg.equals("null"))
							{
								String[] obj=cdimg.split(",");
								for(int k=0;k<obj.length;k++)
								{
									imgNameList.add(obj[k]);
								}
							}
						}
					}
				}
				postImgToThread(imgNameList,"");
				
				//1.更新状态和互检人
				String params = ",'type':'updateTaskStatus','orderNo':'"+orderNo+"','status':'"+status+"','workNo2':'"+workNo2+"'";
				AccessDBImp db= new AccessDBImp();
				db.proDB("updateTaskStatus", params);
				
			}
		}
		  
	}
	
	
	public void postImgToThread(List<String> imgNameList, String resultId)
	{
		for(int i=0;i<imgNameList.size();i++)
		{
			 // /storage/emulated/0/SZGDJT/imgs/  20130901194959.jpg   ,
			String filePath=imgNameList.get(i);
			String saveName=filePath.substring(filePath.lastIndexOf("/")+1);
			
			String url = String.format(
					"%1$s?photoName=%2$s",
					ApplicationGlobal.uploadImageUrl,
					saveName,imgNameList.get(i),
					""
					);		
			UploadItem item = new UploadItem();
			item.setUrl(url);
			Log.d("Check...URL", url);
			item.setPath(imgNameList.get(i));
			item.setTag1(String.valueOf(i+1));
			
			if(i==imgNameList.size()-1)
			{
				item.setTag2("last");
			}
			uploadMultiThread.add(item);
			//ProgressDialogUtil.show(this, "图片上传中", false);
		}
	}
	
	/**
	 * 同步互检人
	 * @throws Exception 
	 */
	private void synPerson() throws Exception
	{
		AccessDBImp dao= new AccessDBImp();
		String re=dao.proDB("getPersonList", ",'userId':'" + ApplicationGlobal.userId + "','type':'getPersonList'");
		ArrayList list  =dao.splitDataList(re);
		for(int i=0;i<list.size();i++ )
		{
			HashMap<String,String> map =(HashMap<String,String>) list.get(i);
			HashMap<String, String> reMap=new HashMap<String, String>();
			reMap.put("user_id", map.get("EMPLOYEE_ID"));
			reMap.put("user_name", map.get("EMPLOYEE_NAME"));
			reMap.put("team_id", map.get("DEPT_ID"));
			DataBaseUtil.insertCheckUserData(reMap);
		}
	} 
	
	
	private Handler handler1 = new Handler() {        
		@Override
        public void handleMessage(Message msg) {
	}};
}
